from flask import Flask,render_template,request,redirect

app = Flask(__name__)
app.config.update(DEBUG=True)
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin, LoginManager, login_user, logout_user, login_required, current_user
import requests
import json
app = Flask(__name__)
app.config['SECRET_KEY'] = 'weather'

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost:3306/weather'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # 关闭对模型修改的监控
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)  # 初始化应用
login_manager.login_view = 'login'  # 设置用户登录视图函数 endpoint




@login_manager.user_loader  # 定义获取登录用户的方法
def load_user(user_id):
    return User.query.get(user_id)

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)  # 主键
    user_name = db.Column(db.String(20))  # 手机号
    password = db.Column(db.String(20))  # 密码

with app.app_context():
    db.create_all()


@app.route("/",methods=["GET"])
@login_required
def index():
    keyword=request.args.get("keyword")
    if keyword is None or keyword=="":
        return render_template("index.html")
    else:

        headers={"X-Bce-Signature":"AppCode/591568078f804c1fb623642271597b39"}
        body={"city":keyword}
        response=requests.get("https://weatherweek.api.bdymkt.com/week",body,headers=headers)
        info=json.loads(response.text)
        dateList=[]
        temp1List=[]
        temp2List=[]
        for i in info['data']:
            dateList.append(i['date'])
            temp1List.append(i['tem1'])
            temp2List.append(i['tem2'])
        info["trend"]={"date":dateList,"temp1":temp1List,"temp2":temp2List}
        return render_template("index.html", keyword=keyword,data=info)


@app.route('/login', methods=['GET', "POST"])
def login():
    if request.method == "POST":
        user_name = request.form.get("user_name")
        password = request.form.get("password")
        user = User.query.filter(User.user_name == user_name).first()
        if user is None:
            msg = "用户不存在"
            return render_template("login.html", msg=msg)
        elif user.password != password:
            msg = "错误密码"
            return render_template("login.html", msg=msg)
        else:
            login_user(user, remember=True)

            return redirect("/")
    return render_template('login.html')


@app.route("/logout/", methods=["GET"])
def logout():

    logout_user()
    return redirect("/")

@app.route('/register', methods=['GET', "POST"])
def register():
    if request.method == "POST":
        user_name = request.form.get("user_name")
        password = request.form.get("password")
        password2 = request.form.get("password2")
        if user_name is None:
            return render_template("register.html", msg="用户名不能为空")
        elif password is None:
            return render_template("register.html", msg="密码不能为空")
        elif password != password2:
            return render_template("register.html", msg="两次密码不一致")
        user = User.query.filter(User.user_name == user_name).first()
        if user is not None:
            return render_template("register.html", msg="该用户已经注册了")

        user = User(user_name=user_name, password=password)
        db.session.add(user)
        db.session.commit()
        return redirect("/login")
    return render_template('register.html')


if __name__ == '__main__':
    app.run()
